<template>
    <div class="content">
        <div class="form">
            <el-button type="primary" size="mini" @click="handleBtn('add')">新增</el-button>
            <el-button size="mini" @click="handleBtn('delete')">删除</el-button>
            <el-button size="mini" @click="handleBtn('refresh')">刷新</el-button>
        </div>
        <RiskTableP
            ref="risk-table"
            :tableConfig="tableConfig"
            :tableData="tableData"
            :column="tableColumns"
            :paging="paging"
            v-loading="tableLoading"
            @page-change="getTableData"
            style="height: calc(100% - 60px)"
        >
            <template #operation="{ row }">
                <RiskIconButton type="primary" icon="el-icon-view" @on-click="handleBtn('look', row)" topTitle="查看" />
                <RiskIconButton type="primary" icon="el-icon-edit" @on-click="handleBtn('update', row)" topTitle="修改" />
            </template>
        </RiskTableP>
        <yh-dialog
            drag
            :title="dialogTitle"
            :visible.sync="dialogVisible"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            width="1000px"
            v-if="dialogVisible"
        >
            <el-form class="form-config" label-width="110px" ref="infoConfig" :model="infoConfig">
                <el-form-item label="通知组名称:" prop="noticeName">
                    <el-input v-model="infoConfig.noticeName" size="mini" class="item" :disabled="dialogType == 'look'"> </el-input>
                </el-form-item>
                <el-form-item label="用户多选:" prop="users">
                    <el-input v-model="infoConfig.users" size="mini" readonly class="item" :disabled="dialogType == 'look'"></el-input>
                    <NotificationSettingTable
                        :ref="'table-user'"
                        :type="'user'"
                        :tableConfigUser="{
                            rowKey: 'userCode', // 主键key
                            allRowKeys: [],
                        }"
                        :infoConfig="infoConfig"
                        :dialogType="dialogType"
                        @checkRowKeys-change="checkRowKeysChange('user', $event)"
                    ></NotificationSettingTable>
                </el-form-item>
                <el-form-item label="角色多选:" prop="roles">
                    <el-input v-model="infoConfig.roles" size="mini" readonly class="item" :disabled="dialogType == 'look'"> </el-input>
                    <NotificationSettingTable
                        :ref="'table-role'"
                        :type="'role'"
                        :tableConfigUser="{
                            rowKey: 'roleCode', // 主键key
                            allRowKeys: [],
                        }"
                        :infoConfig="infoConfig"
                        :dialogType="dialogType"
                        @checkRowKeys-change="checkRowKeysChange('role', $event)"
                    ></NotificationSettingTable>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click="handleBtn('cancelDialog')"> 取 消 </el-button>
                <el-button size="mini" type="primary" @click="handleBtn('confirmDialog')" v-loading="btnLoading" v-if="dialogType != 'look'">
                    确 定
                </el-button>
            </div>
        </yh-dialog>
    </div>
</template>
<script lang="ts">
import RiskTableP from '@/common/components/risk-table-plus.vue';
import { PageVO, TableConfigVO, VueObject } from '@/common/vo';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import NotificationSettingTable from './notification-setting-table.vue';
import API from '../api/process-handling';
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import { dateFormat } from '@/utils/tools';

@Component({ name: 'NotificationGroupManage', components: { RiskTableP, NotificationSettingTable, RiskIconButton } })
export default class NotificationGroupManage extends Vue {
    btnLoading: boolean = false;
    dialogVisible: boolean = false;
    dialogType: string = '';
    infoConfig: any = {
        userGroupNoticeCode: '',
        noticeName: '',
        users: '',
        roles: '',
        userCodes: [],
        roleCodes: [],
    };
    paging: PageVO = {
        currentPage: 1,
        pageSize: 25,
        total: 0,
    };
    tableLoading: boolean = false;
    tableConfig: TableConfigVO = {
        rowKey: 'userGroupNoticeCode', // 主键key
        allRowKeys: [], // 所有页数据的key集合
    };
    tableData: any[] = [];
    tableColumns = [
        { type: 'checkbox', selectedAll: false, width: 60, align: 'center' },
        {
            type: 'seq',
            title: '序号',
            width: '60px',
        },
        {
            title: '编号',
            field: 'userGroupNoticeCode',
            width: '80px',
        },
        {
            title: '通知组名称',
            field: 'noticeName',
        },
        {
            title: '通知角色组',
            field: 'roleName',
        },
        {
            title: '通知用户组',
            field: 'userName',
        },
        {
            title: '创建日期',
            field: 'cdDate',
            render: value => dateFormat(value),
        },
        {
            title: '创建人',
            field: 'ctUser',
        },
        {
            title: '操作',
            field: 'operation',
            fixed: 'right',
            width: 140,
            align: 'center',
        },
    ];

    @Prop() activeValue: string;
    isFirst: boolean = true;
    @Watch('activeValue', { immediate: true })
    handleActiveValue() {
        if (this.activeValue === 'notification-group-manage') {
            if (this.isFirst) {
                this.isFirst = false;
                this.getTableData();
            }
        }
    }
    /**
     * 表格数据
     */
    getTableData() {
        this.tableLoading = true;
        return new Promise((resolve, reject) => {
            API.handleInfoGroupList({ paging: this.paging })
                .then((res: any) => {
                    this.tableData = res?.list || [];
                    this.paging.total = res?.total || 0;
                    resolve(res);
                })
                .catch(err => {
                    console.log(err, 'handleInfoGroupList');
                    // this.tableData = [
                    //     {
                    //         userGroupNoticeCode: 'T001',
                    //         noticeName: '投资经理',
                    //         users: 'xinxin,userAction1',
                    //         roles: '测试黑白名单岗位',
                    //         userCodes: ['781', 'YH_741'],
                    //         roleCodes: ['YH1003'],
                    //         cdDate: '20230630',
                    //         ctuser: 'administrator',
                    //     },
                    //     { userGroupNoticeCode: '1212' },
                    // ];
                    // this.paging.total = 2;
                    reject(err);
                })
                .finally(() => {
                    this.tableLoading = false;
                });
        });
    }

    get dialogTitle() {
        let typeName = '';
        if (this.dialogType == 'add') {
            typeName = '新增';
        } else if (this.dialogType == 'update') {
            typeName = '修改';
        } else if (this.dialogType == 'look') {
            typeName = '查看';
        }
        return typeName + '通知配置';
    }

    /**
     * 按钮操作
     */
    async handleBtn(type: string, row?: any) {
        if (type === 'add') {
            this.dialogVisible = true;
            this.infoConfig = {
                userGroupNoticeCode: '',
                noticeName: '',
                users: '',
                roles: '',
                userCodes: [],
                roleCodes: [],
            };
            this.dialogType = type;
        } else if (type == 'delete') {
            const checkRowKeys = (this.$refs['risk-table'] as VueObject).checkRowKeys;
            if (checkRowKeys.length < 1) {
                this.yh_message_info(`请先勾选需删除的数据！`);
                return;
            }
            API.handleInfoGroupDelete({ userGroupNoticeCodes: checkRowKeys }).then(() => {
                this.yh_message_success('删除成功!');
                this.paging.currentPage = 1;
                this.getTableData();
            });
        } else if (type == 'refresh') {
            this.paging.currentPage = 1;
            await this.getTableData();
            this.yh_message_success('刷新成功！');
        } else if (type == 'look' || type == 'update') {
            for (let key in this.infoConfig) {
                if (Array.isArray(this.infoConfig[key])) {
                    this.infoConfig[key] = row[key] || [];
                } else {
                    this.infoConfig[key] = row[key] || '';
                }
            }
            console.log(this.tableData, row, this.infoConfig, 'infoConfig-------------');
            this.dialogType = type;
            this.dialogVisible = true;
        } else if (type == 'confirmDialog') {
            if (!this.infoConfig.noticeName) {
                this.yh_message_error('通知组名称不可为空！');
                return;
            }
            if (!this.infoConfig.userCodes.length && !this.infoConfig.roleCodes.length) {
                this.yh_message_error('用户或者角色两者必须选择一项');
                return;
            }
            this.btnLoading = true;
            const executeMethod = this.dialogType == 'add' ? API.handleInfoGroupAdd : API.handleInfoGroupUpdate;
            executeMethod(this.infoConfig)
                .then(() => {
                    this.dialogVisible = false;
                    this.yh_message_success(this.dialogType == 'add' ? '新增成功！' : '修改成功！');
                    this.getTableData();
                })
                .catch(err => {
                    console.log(err, 'handleInfoGroupAdd');
                })
                .finally(() => {
                    this.btnLoading = false;
                });
        } else if (type == 'cancelDialog') {
            this.dialogVisible = false;
        }
    }

    /**
     * 勾选值变化时
     */
    checkRowKeysChange(type, $event) {
        console.log($event, '$event');
        const { keys, values } = $event;
        if (type === 'user') {
            this.infoConfig.userCodes = keys;
            this.infoConfig.users = values.toString();
        } else {
            this.infoConfig.roleCodes = keys;
            this.infoConfig.roles = values.toString();
        }
        console.log(this.infoConfig.roles, ' this.infoConfig.roles');
    }
}
</script>
<style lang="scss" scoped>
.content {
    height: 100%;
    .form {
        border: 1px solid #ccc;
        padding: 8px;
        margin-bottom: 10px;
    }
}

.form-config {
    width: 96%;
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    .el-form-item {
        margin-bottom: 10px;
        &:first-child {
            grid-column: 1 / 3;
            grid-row: 1 / 2;
        }
    }
    .item {
        width: 100%;
    }
}
.dialog-footer {
    text-align: right;
    margin-right: 20px;
}
</style>
